package com.ibeeking.found.id;

import com.ibeeking.found.id.api.feign.IdFeignClient;
import com.ibeeking.nematos.redis.utils.RedisUtils;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.id.IdGenerator;
import com.ibeeking.nematos.utils.result.ResponseResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @ClassName RedisUtil
 * @Description redis工具类
 * @Author ibeeking
 * @Date 2020-04-26 13:24
 **/
@Component
@RefreshScope
public class GenerateId {

    private static final String SNOWFLAKE_ID = "SNOWFLAKE:ID";

    private static Integer idCount;

    private static RedisUtils redisUtils;

    private static IdFeignClient idFeignClient;

    public GenerateId(RedisUtils redisUtils, IdFeignClient feignClient) {
        GenerateId.redisUtils = redisUtils;
        GenerateId.idFeignClient = feignClient;
    }

    public static Long generateId() {
        Object o = redisUtils.lLeftPop(SNOWFLAKE_ID);
        if (null == o) {
            ResponseResult<List<Object>> responseResult = idFeignClient.selectIds(GenerateId.getIdCount());
            if (Collections3.isEmpty(responseResult.getData())) {
                return IdGenerator.getId();
            } else {
                redisUtils.lSet(SNOWFLAKE_ID, responseResult.getData());
            }
            o = redisUtils.lLeftPop(SNOWFLAKE_ID);
        }
        return null == o ? IdGenerator.getId() : (Long) o;
    }

    private static Integer getIdCount() {
        return idCount;
    }

    @Value("${ibeeking.idCount:2000}")
    private void setIdCount(Integer idCount) {
        GenerateId.idCount = idCount;
    }
}